package com.ubing.boot.notesforjava.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ubing.boot.notesforjava.dao.TestMapper;
import com.ubing.boot.notesforjava.dao.UserInfoMapper;
import com.ubing.boot.notesforjava.domel.entity.NoteInfo;
import com.ubing.boot.notesforjava.domel.entity.Test;
import com.ubing.boot.notesforjava.domel.entity.UserInfo;
import com.ubing.boot.notesforjava.domel.entity.UserSensitive;
import com.ubing.boot.notesforjava.listener.MyApplicationListener;
import com.ubing.boot.notesforjava.listener.MyListener;
import com.ubing.boot.notesforjava.response.Response;
import com.ubing.boot.notesforjava.scheduled.MyScheduledTask;
import com.ubing.boot.notesforjava.service.INoteInfoService;
import com.ubing.boot.notesforjava.service.IUserInfoService;
import com.ubing.boot.notesforjava.service.impl.INoteInfoServiceImpl;
import com.ubing.boot.notesforjava.test.NIO.test_common;
import com.ubing.boot.notesforjava.test.excel;
import com.ubing.boot.notesforjava.test.juc.A;
import com.ubing.boot.notesforjava.test.juc.FixedSizeList;
import com.ubing.boot.notesforjava.utils.RedisUtils;
import com.ubing.boot.notesforjava.utils.SensitiveUtils;
import org.apache.catalina.core.ApplicationContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ubing
 * @since 2023-02-20
 */
@RestController
@RequestMapping("/noteInfo")
public class NoteInfoController {

    @Autowired
    INoteInfoService iNoteInfoService;

    @RequestMapping("/insert")
    public Response insert(@RequestBody NoteInfo noteInfo){
        return iNoteInfoService.insert(noteInfo);
    }


    @RequestMapping("/detail")
    public Response detail(String noteId){
        return iNoteInfoService.detail(noteId);
    }

    @RequestMapping("/getListById/{pageNo}/{pageSize}")
    public Response getListById(@PathVariable Integer pageNo,@PathVariable Integer pageSize, @RequestBody NoteInfo noteInfo){
        return iNoteInfoService.getListById(pageNo,pageSize,noteInfo);
    }

    @Autowired
    ThreadPoolExecutor executor;
    @Autowired
    UserInfoMapper userInfoMapper;
//    private  static final Object lock=new Object();
    @RequestMapping("/getList/{pageNo}/{pageSize}")
    public Response getList(@PathVariable Integer pageNo,@PathVariable Integer pageSize) throws ExecutionException, InterruptedException {
//        List<List<UserInfo>> responses = new LinkedList<>(); // 使用线程安全的CopyOnWriteArrayList
//        CountDownLatch latch = new CountDownLatch(1000); // 使用 CountDownLatch
//        ReentrantLock lock = new ReentrantLock();
//////        CompletableFuture<List<UserInfo>> submit = null;
////        for (int i = 0; i < 1000; i++) {
////            executor.execute(()->{
////                List<UserInfo> ubing = userInfoMapper.selectList(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getUserName, "ubing"));
////                synchronized (lock){
////                    responses.add(ubing);
////                }
////                latch.countDown();
////            });
////        }
////        latch.await();
//        System.out.println(responses.size());
//        return Response.success(responses);

        return iNoteInfoService.getList(pageNo,pageSize);
    }

    @Autowired
    RedisTemplate<String, Object> redisTemplate;
    @Autowired
    IUserInfoService IUserInfoService;
    @Autowired
    test_common test_common;
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    @Autowired
    INoteInfoServiceImpl iNoteInfoServiceImpl;
    @RequestMapping("/excel")
    public Response excel(HttpServletResponse response) throws IOException {
//        redisTemplate.opsForValue().set("user1", IUserInfoService.getOne(new QueryWrapper<UserInfo>().eq("user_name","ubing")));
//        Object user = redisUtils.get("user");

        Object o = redisTemplate.opsForValue().get("user");
        System.out.println(o);
        Set<String> keys = redisTemplate.keys("user*");
        List list = redisTemplate.opsForValue().multiGet(keys);
        System.out.println(list);


//        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
//        applicationContext.register(MyApplicationListener.class);
        applicationEventPublisher.publishEvent(new MyListener("自定义事件"));
//        applicationContext.refresh();
//        iNoteInfoServiceImpl.test();
        return Response.success(o);

    }


    @Autowired
    TestMapper testMapper;
    @RequestMapping("/setList")
    public Response setList() throws IOException {
        redisTemplate.opsForList().leftPush("list", "1");
        redisTemplate.opsForList().leftPush("list", "2");
        redisTemplate.opsForList().leftPush("list", "3");
        UpdateWrapper<Test> testUpdateWrapper = new UpdateWrapper<Test>()
                .set("name", "123");
        testMapper.update(null,testUpdateWrapper);
        return Response.success();

    }

    @RequestMapping("/getList")
    public Response getList() throws IOException {
        Object o = redisTemplate.opsForList().rightPop("list");
        return Response.success(o);

    }

    @RequestMapping("/excel1/{s}")
    public void excel1(HttpServletResponse response,@PathVariable String s) throws IOException {
        Path path = Paths.get("E:\\GitHub\\notesforjava\\src\\main\\java\\com\\ubing\\boot\\notesforjava\\test\\excel.txt");
        Stream<String> lines = Files.lines(path);
        String collect = lines.collect(Collectors.joining(System.lineSeparator()));
        String[] split = collect.split("<formelement");
        String regex;

        if(s.equals("1")){
            regex = "fieldname=\\\"\\S*";
            regex="F\".\"\\S*\"";
        }else {
            regex = "labelname=\\\"\\S*";
        }
        System.out.println(regex);
        List<excel> list= new ArrayList<>();
        for (int i = 0; i < split.length; i++) {
            final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);

            final Matcher matcher = pattern.matcher(split[i]);
            boolean flag=false;
            while (matcher.find()) {
                    list.add(new excel(matcher.group(0).substring(4,matcher.group(0).length()-1),""));
                flag=true;
            }
            if(!flag) {
                list.add(new excel("1",""));
            }
        }
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("UTF-8");
        String fileName = "项目信息";
        EasyExcel.write(response.getOutputStream()).excelType(ExcelTypeEnum.XLSX).sheet(fileName).doWrite(list);
    }

    @RequestMapping("/excel2/{aa}/{s}")
    public void excel2(HttpServletResponse response,@PathVariable String s,@PathVariable String aa) throws IOException {
        String regex = aa+"\\\".\\\"\\S*";
        regex="  \\\"\\S*";
        Path path = Paths.get("E:\\GitHub\\notesforjava\\src\\main\\java\\com\\ubing\\boot\\notesforjava\\test\\excel.txt");
        if(s.equals("1")){
            Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
//            Path path = Paths.get("E:\\GitHub\\notesforjava\\src\\main\\java\\com\\ubing\\boot\\notesforjava\\test\\excel.txt");
            Stream<String> lines = Files.lines(path);
            String string = lines.reduce("",(a,b)->a+b);
            Matcher matcher = pattern.matcher(string);
            List<excel> list= new ArrayList<>();
            while (matcher.find()) {
                String group = matcher.group(0);
                String substring = group.substring(3, group.length() - 1);
                list.add(new excel(substring,""));
                System.out.println(substring);
                for (int i = 1; i <= matcher.groupCount(); i++) {
                    System.out.println(matcher.group(i));
                }
            }
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            String fileName = "项目信息";
            EasyExcel.write(response.getOutputStream()).excelType(ExcelTypeEnum.XLSX).sheet(fileName).doWrite(list);
        }
        else if(s.equals("2")){
            regex = "IS '\\S*";
            regex= "\" \\S*";
            Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
            Stream<String> lines = Files.lines(path);
            String string = lines.reduce("",(a,b)->a+b);
            Matcher matcher = pattern.matcher(string);
            List<excel> list= new ArrayList<>();
            while (matcher.find()) {
                String group = matcher.group(0);
                String s1 = group.replaceAll("\" ", "");
                list.add(new excel(s1,""));
            }
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            String fileName = "项目信息";
            EasyExcel.write(response.getOutputStream()).excelType(ExcelTypeEnum.XLSX).sheet(fileName).doWrite(list);

        }else if(s.equals("3")){
            regex=" IS '\\S*;";
            Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
//            Path path = Paths.get("E:\\GitHub\\notesforjava\\src\\main\\java\\com\\ubing\\boot\\notesforjava\\test\\excel.txt");
            Stream<String> lines = Files.lines(path);
            String string = lines.reduce("",(a,b)->a+b);
            Matcher matcher = pattern.matcher(string);
            List<excel> list= new ArrayList<>();
            while (matcher.find()) {

                String group = matcher.group(0);
                String substring = group.replaceAll(" IS '", "").replaceAll("';","");
                list.add(new excel(substring,"substring2"));
            }
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            String fileName = "项目信息";
            EasyExcel.write(response.getOutputStream()).excelType(ExcelTypeEnum.XLSX).sheet(fileName).doWrite(list);
        }

    }
}

